<?php

namespace App\Http\Controllers\Api\Openapi;

use App\Http\Controllers\Controller;
use App\Models\Alert;
use App\Models\File;
use App\Models\Snapshot;
use App\Support\ChunkUpload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ImageController extends Controller
{
    public function index(Request $request)
    {/*
        $prossess = new Process('ls -al');
        $s = $prossess->run(function ($type, $buffer){
            echo $type.PHP_EOL;
            echo Process::ERR.PHP_EOL;

            if (Process::ERR === $type) {
                echo 'ERR > '.$buffer;
            } else {
                echo 'OUT > '.$buffer;
            }

        });
*/
        $key = "zhongjiao";
        $num = 2;
        $data = $request->only(['last_id', 'token']);
        if ($data['token'] != $key) {
            return response()->json(['status' => 300, 'msg' => '数据为空']);
        }
        if (isset($data['last_id']) && is_numeric($data['last_id'])) {
            $images = Snapshot::where('id', '>', $data['last_id'])->limit($num)->get();
        } else {
            $images = Snapshot::limit($num)->get();
        }
        $images->each(function (&$item) {
            $item->image = File::getFileUrl($item->image);
        });

        //return response()->json(['status'=>200, 'data'=>$images]);
    }

    /**
     * 记录报警
     *  http://localhost:8123/api/open/alert
     *
     * @param Request $request
     * @throws \Illuminate\Validation\ValidationException
     */
    public function alert(Request $request)
    {
        $validate = [
            'img' => 'image',
            'pid' => 'required',
            'content' => 'required',
            'time_stamp' => 'required|numeric'
        ];

        $this->validate($request, $validate, [], [
            'img' => "图片",
            'content' => "报警信息",
            'pid' => "摄像头编号",
            'time_stamp' => "时间戳"
        ]);

        $data = $request->only(['img', 'content', 'pid', 'time_stamp']);

        if ($request->hasFile('img')) {
            $file = $request->file('img');
            $uploader = new ChunkUpload();
            $filePath = $uploader->setType('image')->upload($file);
            if ($filePath === false) {
                return back()->withErrors(['img' => __('Img upload failed')])->withInput();
            }
            $data['img'] = $filePath;
        }

        if (Alert::insert($data)) {
            return response()->json(['code'=>200, 'msg'=>"success"]);
        }

        Log::error("save false".json_encode($data));

        return response()->json(['code'=>102, 'msg'=>"error"]);

    }
}
